// pages/movies/more-movies/more-movies.js
import * as utils from '../../../utils/util'
const app = getApp();
let that;
Page({

   /**
    * 页面的初始数据
    */
   data: {
      movies: {},
      navigateTitle: '',
      totalCount: 0,
      requestUrl: '',
      isEmpty: true,
   },

   /**
    * 生命周期函数--监听页面加载
    */
   onLoad: function (options) {
      that = this;
      const category = options.category;
      console.log(category);

      that.setData({
         navigateTitle: category
      })
      let dataUrl = app.globalData.g_doubanBase;
      switch (category) {
         case "正在热映":
            dataUrl = dataUrl + "/v2/movie/in_theaters";
            break;
         case "即将上映":
            dataUrl = dataUrl + "/v2/movie/coming_soon";
            break;
         case "top250":
            dataUrl = dataUrl + "/v2/movie/top250";
            break;
      }

      that.setData({
         requestUrl: dataUrl
      });

      utils.http(dataUrl, that.processDoubanData);

   },



   processDoubanData: (moviesDouban) => {
      const movies = [];
      for (let idx in moviesDouban.subjects) {
         const subject = moviesDouban.subjects[idx];
         let title = subject.title;
         if (title.length >= 6) {
            title = title.substring(0, 6) + '...';
         }
         const temp = {
            stars: utils.convertToStarsArray(subject.rating.stars),
            title: title,
            average: subject.rating.average,
            coverageUrl: subject.images.large,
            movieId: subject.id
         }

         movies.push(temp);
      }
      
      //合并数据
      let totalMovies = {};
      if (!that.data.isEmpty) {
         totalMovies = that.data.movies.concat(movies);
      } else {
         totalMovies = movies;
         that.data.isEmpty = false;
      }

      that.setData({
         movies: totalMovies,
         totalCount: that.data.totalCount+=20
      });


     // wx.hideNavigationBarLoading();
     wx.hideToast();
     wx.stopPullDownRefresh();
   },


   onReachBottom: (event) => {
      const nextUrl = that.data.requestUrl + "?start=" + that.data.totalCount + "&count=20";

      utils.http(nextUrl, that.processDoubanData);

      wx.showToast({
         title: '',
         icon:'loading',
         mask:true,
      });
      wx.stopPullDownRefresh();
   },

   onPullDownRefresh:(event)=>{
      const refreshUrl = that.data.requestUrl+"?start=0&count=20";
      that.setData({
        movies:{},
        isEmpty:true,
        totalCount:0
      });
      utils.http(refreshUrl, that.processDoubanData);

   },

   onReady: (event) => {
      wx.setNavigationBarTitle({
         title: that.data.navigateTitle,
      })
   },


   onMovieTap:(event)=>{
    const movieId = event.currentTarget.dataset.id;
    console.log(movieId);
    wx.navigateTo({
      url: '../movie-detail/movie-detail?id='+movieId,
    })
  },

})